#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "init.h"
#include "tool.h"
#include "valloc.h"
#include "calculate.h"
#include <float.h>
#include <math.h>
#include "command.h"
#include <math.h>
#include <ctype.h>

static int command_calculate(int argc, char *argv[])
{
    double r = NAN;
    if (argc < 2) return 0;
    r = calculate(argv[1]);
    if (fabs(floor(r) - r) <= DBL_EPSILON && fabs(r) < 1.0e60) printf("%.0lf\r\n", r);
    else if (fabs(r) < 1.0e-6 || fabs(r) > 1.0e9) printf("%e\r\n", r);
    else 
    {
        char p[64];
        int len = 0;
        len = sprintf(p, "%lf", r);
        while (len > 0 && p[len-1] == '0' && p[len-2] != '.') {p[--len] = 0;}
        printf("%s\r\n", p);
    }
    return 1;
}

static double factorial(double n)
{
    if (n < 1) return 1;
    return n * factorial(n - 1);
}

static double K()
{
    return 1024.0;
}

static void test(void)
{
    printf("mul %lf\r\n", calculate("    ( 99 * 3 ) "));
    printf("min %lf\r\n", calculate("  min  (12, 3)"));
    printf("sin %lf\r\n", calculate("sin (  11 / 2 *  pi ) + 100 "));
    
    calculate_export("fac", factorial, 1);
    calculate_export("K", K, 0);
    
    command_export("cal", command_calculate);
}
init_export_app(test);
